// ignore_for_file: must_call_super

import 'dart:io';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:xvideos/hj_page/video/view/video_menu_view.dart';
import 'package:xvideos/tools_base/appbar/base_app_bar.dart';
import 'package:xvideos/tools_base/loading/loading_center_widget.dart';
import 'package:xvideos/hj_utils/global.dart';
import 'package:video_player/video_player.dart';

import '../../tools_base/debug_log.dart';
import 'video_full_page.dart';

class SimpleVideoPlayerPage extends StatefulWidget {
  final String videoUrl;
  final String title;
  final String? localPath;

  const SimpleVideoPlayerPage({super.key, required this.videoUrl, required this.title, this.localPath});

  @override
  State<StatefulWidget> createState() {
    return _SimpleVideoPlayerPageState();
  }
}

class _SimpleVideoPlayerPageState extends State<SimpleVideoPlayerPage> {
  VideoPlayerController? videoPlayerController;

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      _initData();
    });
  }

  void _initData() async {
    try {
      if (widget.localPath?.isNotEmpty == true) {
        videoPlayerController = VideoPlayerController.file(File(widget.localPath ?? ""));
      } else {
        debugLog('url=${widget.videoUrl}');
        videoPlayerController = VideoPlayerController.networkUrl(Uri.parse(widget.videoUrl));
      }
      await videoPlayerController?.initialize();
      videoPlayerController?.play();
      if (mounted) {
        setState(() {});
      }
    } catch (e) {
      showToast("视频加载失败");
    }
  }

  @override
  void dispose() {
    super.dispose();
    videoPlayerController?.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        backgroundColor: Colors.black,
        appBar: BaseAppBar(
          title: widget.title,
          backgroundColor: Colors.black,
        ),
        body: Center(
          child: SimpleVideoPlayerView(videoPlayerController),
        ));
  }
}

class SimpleVideoPlayerView extends StatelessWidget {
  final VideoPlayerController? videoPlayerController;
  final double? aspectRatio;
  SimpleVideoPlayerView(this.videoPlayerController, {this.aspectRatio});

  @override
  Widget build(BuildContext context) {
    if (videoPlayerController?.value.isInitialized != true) {
      return LoadingCenterWidget();
    }
    return AspectRatio(
      aspectRatio: aspectRatio ?? videoPlayerController!.value.aspectRatio,
      child: Stack(
        fit: StackFit.expand,
        children: [
          VideoPlayer(videoPlayerController!),
          VideoMenuView(
            controller: videoPlayerController!,
            callback: () async {
              await Get.to(VideoFullPage(controller: videoPlayerController!));
            },
          ),
        ],
      ),
    );
  }
}
